<?php
namespace Dft\Controllers;

use Imagick;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class AssetCSP implements ControllerProviderInterface {

	public function connect(Application $app) {
		$controllers = $app['controllers_factory'];
		$controllers->match('/image/{id}/', array($this,'image'), 'GET')->bind('view-image-original');
		$controllers->match('/image/{id}/{size}/', array($this,'image'), 'GET')->bind('view-image');
		$controllers->match('/download/{id}/', array($this,'download'), 'GET')->bind('download');
		return $controllers;
	}

	public function image(Application $app, Request $request, $id, $size = null) {
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$content = $repo->data('Asset', 'entity.id = ' . $id);
		if (count($content['_data']) == 0) {
			$app->abort(404);
		}
		$fileType = $content['_data'][0]['fileType'];
		$fileName = $content['_data'][0]['name'];
		$file = dirname($_SERVER['SCRIPT_FILENAME']) . '/../uploads/' . $content['_data'][0]['nameOnServer'];
		if ((file_exists($file) && getimagesize($file) && $size) || ('application/pdf' == $fileType)) {
			$size = $repo->data('Thumbnail size', 'entity.width = :v1', array('v1' => $size));
			if (count($size['_data']) == 0) {
				$app->abort(404);
			}
			$cache = dirname($_SERVER['SCRIPT_FILENAME']) . '/../cache/image/';
			if (! file_exists($cache)) {
				mkdir($cache, 0777, true);
			}
			$thumbnail = $cache . md5($content['_data'][0]['id'] . '-' . $size['_data'][0]['width']) . (('application/pdf' == $fileType) ? '.jpg' : '.' . $content['_data'][0]['fileExt']);
// 			if (! file_exists($thumbnail)) {
// 				$myfile = fopen($file, "r") or die("Unable to open file!");
// 				$in = fread($myfile, filesize($file));
// 				$descriptorspec = array(0 => array("pipe","r"),1 => array("pipe","w"),2 => array("file",$cache . '/error.log','a'));
// 				$process = proc_open(IMAGICK . ' ' . $file . ' -strip -interlace Plane -gaussian-blur 0.05 -quality 85% -resize "' . $size['_data'][0]['width'] . 'x' . $size['_data'][0]['width'] . '>" ' . $thumbnail, $descriptorspec, $pipes);
// 				if (is_resource($process)) {
// 					fwrite($pipes[0], $in);
// 					fclose($pipes[0]);
// 					fclose($pipes[1]);
// 					proc_close($process);
// 				}
// 			}
			if (!file_exists($thumbnail)) {
				if ('application/pdf' == $fileType) {
					$image = new imagick($file . '[0]');
					$image->setImageFormat('jpg');
					$image->setColorspace(imagick::COLORSPACE_RGB);
					$image->thumbnailImage($size['_data'][0]['width'], null);
					$image->writeImage($thumbnail);
				} else {
					$image = new Imagick($file);
					$image->adaptiveResizeImage($size['_data'][0]['width'], 0);
					$image->writeImage($thumbnail);
				}
			}
			$file = $thumbnail;
		}
		if (! file_exists($file) || ! getimagesize($file)) {
			$file = dirname($_SERVER['SCRIPT_FILENAME']) . '/../../_cdn/htdocs/default/images/noimage.jpg';
		}
		$stream = function () use($file) {
			readfile($file);
		};
		return $app->stream($stream, 200, array(
			'Content-Type' => 'image/jpg',
			'Content-length' => filesize($file),
			'Content-Disposition' => 'filename="' . $fileName . '"'
		));
	}

	public function download(Application $app, $id) {
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$content = $repo->data('Asset', 'entity.id = ' . $id);
		if (count($content['_data']) == 0) {
			$app->abort(404, "Asset not found");
		}
		$fileType = $content['_data'][0]['fileType'];
		$fileName = $content['_data'][0]['name'];
		$file = dirname($_SERVER['SCRIPT_FILENAME']) . '/../uploads/' . $content['_data'][0]['nameOnServer'];
		$stream = function () use($file) {
			readfile($file);
		};
		return $app->stream($stream, 200, array(
			'Content-Type' => $fileType,
			'Content-length' => filesize($file),
			'Content-Disposition' => 'attachment; filename="' . (($preview) ? 'preview.gif' : $fileName) . '"'
		));
	}
}